<?php
namespace Admin\Controller;
use Think\Controller;
/*
 * 全局控制器
 * */


class GroupsController extends BaseController {
	/******
	//  session 数据
			[aomai_sess_id_define01] => 3a0f93bb29e97762c762391eb47f7c3f
			[user_id] => 0
			[user_name] => 
			[email] => 
			[user_rank] => 0 
			[discount] => 1 
			[captcha_word] => OTIwZGZjOTZlNQ== 
			[admin_id] => 1 
			[admin_name] => admin 
			[action_list] => all 
			[last_check] => 1463047391 
			[suppliers_id] => 0
			*****/

			public $song = 1;
	//拼团包一览
			public function groupList(){
				$m=M("group_purchase_package");
				extract(I("request."));
				if(I("request.listrows"))
				{
					$where['listrows']=I("request.listrows");

				}
				if($keywords)
				{
					$wheres['packagename']=array('like',"%".$keywords."%");
				}
				if($isaccord !='')
				{
					$wheres['isaccord']=$isaccord;
				}
				$wheres['isactive']=array('lt',3);
				if($isactive !='')
				{
					$wheres['isactive']=$isactive;
					$wheres['usertype']=0;
				}
				if($start_time)
				{
					$wheres['starttime|addtime']=array('egt',$start_time." 00:00:01");
				}
				if($end_time)
				{   
					$wheres['endtime|addtime']=array('elt',$end_time." 23:59:59");
				}
		    /* if($start_time && $end_time)
		    {
				$wheres['starttime|addtime']=array('egt',$start_time);
			    $wheres['endtime|addtime']=array(array('egt',$start_time),array('elt',$end_time),"and");
			} */
			if($blongtype)
			{
				$wheres['blongtype']=$blongtype;
			}
			$where['where']=$wheres;
			$where['order']="gpp.addtime desc";
			$where['field']="gpp.*,au.user_name,u.user_name as username";
			$where['alias']="gpp";
			$where['join']="left join ".$this->dbprefix."admin_user as au on au.user_id = gpp.adminuserid left join ".$this->dbprefix."users as u on u.user_id = gpp.userid";
			$count=$m->where($wheres)->count();
			//echo $m->getLastSql();
			$results = $this->_getListsViewSpecial($m, $where);
			//echo $m->getLastSql();
			$this->assign("results",$results['lists']);
			$this->assign("show",$results['page_html']);
			$this->assign("count",$count);
			$this->display();
		}

		public function addGroup(){
			extract(I("param."));
			$this->groupPic("group_desc");
			$this->assign("adminuserid",$_SESSION['admin_id']);
			$this->assign("admin_name",$_SESSION['admin_name']);
			$this->assign("blongtype",$blongtype);
			$this->display();
		}

		public function goodslist(){
			extract(I("param."));
			$m=M("group_purchase");
			if($listrows)
			{
				$where['listrows']=$listrows;

			}
			if($goodsname)
			{
				$wheres['g.goods_name|g.goods_sn']=array("like","%".$goodsname."%");
			}
			$wheres['gp.blongtype']= $blongtype;
			$where['where']=$wheres;
			$where['order']="gp.addtime desc";
			$where['field']="g.goods_id as goodsid,g.goods_sn,g.goods_name,g.retail_price,g.shop_price,g.vip_price ,REPLACE(g.goods_name,'\'','’') AS goods_name";
			$where['join']="inner join ki_goods as g on g.goods_id = gp.goodsid";
			$where['alias']="gp";
			$results = $this->_getListsViewSpecial($m, $where);
			//echo $m->getLastSql();
			if(!empty($id))
			{
				$sqllist=M("group_package_goods")->alias("gpg")->join("inner join ".$this->dbprefix."goods as g on g.goods_id = gpg.goodsid")->where("packageid = '".$id."'")->field("gpg.*,REPLACE(g.goods_name,'\'','’') AS  goodsname")->select();
				if(!empty($sqllist)){
					
					$this->assign('sqllist',json_encode($sqllist));
				}	
			}
			
			$this->assign("blongtype",$blongtype);
			$this->assign("results",$results['lists']);
			$this->assign("show",$results['page_html']);
			$this->display();

		}

		public function edit(){
			extract(I("param."));
			
			$result=M("group_purchase_package")->where("packageid ='".$id."' and blongtype = '".$blongtype."'")->find();
		   //包详情信息
			$this->groupPic("group_desc",$result['group_desc']);
		   //获得该包的商品
			$results=M("group_package_goods")->alias("gpg")->join("inner join ".$this->dbprefix."goods as g on g.goods_id = gpg.goodsid inner join ".$this->dbprefix."admin_user as au on au.user_id = gpg.adminuserid")->where("gpg.packageid ='".$id."'")->field("gpg.*,g.goods_name,au.user_name")->select();
		   //获得该包的图片
			$imgs=M("group_gallery")->alias("gg")->join("inner join ".$this->dbprefix."attachment as att on att.file_name = gg.img_url")->where("gg.packageid ='".$id."' and module ='group'")->field("att.id,att.file_name,gg.img_id,gg.img_sort")->select();
			$this->assign("result",$result);
			$this->assign("imgs",$imgs);
			$this->assign("results",$results);
			$this->assign("blongtype",$blongtype);
			$this->assign("adminuserid",$_SESSION['admin_id']);
			$this->assign("admin_name",$_SESSION['admin_name']);
            //编辑变量
			$this->assign("edit",$edit);
			if($type=="group")
			{
				$this->display("group");
			}
			else{
				$this->display("addGroup");
			}
		}

	//添加、修改团包
		public function doGroup(){


			$ret=array('staute'=>'error','msg'=>"保存失败");
			$parcel=$_POST['data'];
			$postdata=I("json");
			$m=M("group_purchase_package");

			if(empty($parcel)||empty($postdata)){
				$ret=array('staute'=>'error','msg'=>"传输参数错误");
				$this->ajaxReturn ($ret);
				exit;
			} 
			//$group = json_decode($parcel,true);
			$json = json_decode($postdata,true);
			if(!is_array($json)){
				$ret=array('staute'=>'error','msg'=>"团包商品信息错误");
				$this->ajaxReturn ($ret);
				exit;
			}
			//对团购包或预售包数据进行处理
			$retgroup=$retadd=$retupd= $retdel=1; //默认是成功状态
			
		   $m->startTrans(); //启动事务$i=0
		   $j=0;
		   for($i=0;$i< count($parcel);)
		   {

		   	if($parcel[$i]['name']=="gallery_img_pic[]")
		   	{
		   		$pic_id[$j]['id']=$parcel[$i]['value'];
		   		$pic_id[$j]['img_sort']=$parcel[$i+1]['value'];
		   		if(strstr($parcel[$i+2]['name'],"id"))
		   		{
		   			$pic_id[$j]['img_id']=$parcel[$i+2]['value'];
		   			$i=$i+3;
		   		}
		   		else
		   		{
		   			$i=$i+2;
		   		}
		   		$j++;
		   	}
		   	else
		   	{
		   		$data[$parcel[$i]['name']]=$parcel[$i]['value'];
		   		$i++;
		   	} 
		   }
		  /*  foreach($parcel as $key => $val)
		   {
			    
				//$data[preg_replace("/sum([SUV])/e",'strtolower("$1")',$val['name'])]=$val['value'];
				if($val['name'] == "gallery_img_pic[]")
				{
					$pic_id[]['id']=$val['value'];
					$pic_id[]['id']=$val['value'];
				}
				else
				{
					$data[$val['name']]=$val['value'];
				}
			} */
			$data['addtime']=date("Y-m-d H:i:s");
			$data['adminuserid']=$_SESSION['admin_id'];
		   //倍数
			$multiple = $data['multiple'];
			unset($data['multiple']);
			if($data['packageid']){

				$retgroup=$m->save($data);
			}
			else
			{
				
				$data['isactive']=1;
				$data['packageid']=getGuid();
				$retgroup=$m->add($data);

				$loop_num = $data['groupnumber'];

				if($this->song!=1){
					$loop_num =1;
				}

               //随机用户
				$this->setUser($data['packageid'],$loop_num);
			}
			$aryadd=$aryupd=array();
			$sqladd=$sqlupd="";
			$where['packageid'] = empty($data['packageid'])?$retgroup:$data['packageid'];
		   //保存图片开始
			if(!empty($pic_id))
			{
				foreach ($pic_id as $key=>$v){ 
					$v["img_url"]=M("attachment")->where("id = '".$v['id']."' and module = 'group'")->getField("file_name");
					if(!empty($v['img_id'])){
						$aryupd[]=$v;
					}
					else
					{
						$v["packageid"]=$where['packageid'];
						$aryadd[]=$v;
					}
				} 
			}
		  //修改

		 //构建插入数据语句
			if(count($aryadd)>0){
				$sqlval=""; 
				$i=1;
				foreach ($aryadd as $k=>$v){
		 		//$listid=getGuid();//创建guid值
		 		//$money = intval($v['number'])*$v['price'] + $v['logistics_price']*$v['weight'];
					if(empty($v['img_sort']))
					{
						$v['img_sort']=$i;
						$i++;
					}
					$sqlval.=((empty($sqlval)?"":",")."('".$v['packageid']."','".$v['img_url']."','".$v['img_sort']."',".time().")");
				}
				$sqladd=" INSERT INTO  ".$this->dbprefix."group_gallery(`packageid`,`img_url`,`img_sort`,add_time) values ".$sqlval;
			}

		 //构建更新数据语句

			if(count($aryupd)>0){ 
				$i=1;		 
				foreach ($aryupd as $k=>$v){
					if(empty($v['img_sort']))
					{
						$v['img_sort']=$i;
						$i++;
					}
		 		//$money = intval($v['number'])*$v['price'] + $v['logistics_price']*$v['weight'];
					$sqlupd="update ".$this->dbprefix."group_gallery set img_url='".$v['img_url']."',img_sort='".$v['img_sort']."',add_time = ".time()." where img_id=".$v['img_id'];
					$arysqlupd[]=$sqlupd;
				} 
			}
		 $gmadd=$gmupd=1; //默认是成功状态
		 $gm=M("group_gallery");
		 $gm->startTrans(); //启动事务
		 
		 if($sqladd){
		 	$gmadd= $gm->execute($sqladd);
		 } 
		 
		 if(count($arysqlupd)>0){
		 	foreach ($arysqlupd as $k=>$sql){
		 		if(empty($sql))continue;
		 		$gmupd= $gm->execute($sql);
			    //如果失败就退出循环，失败
		 		if(!$gmupd){
		 			break;  
		 		}
		 	}
		 }
		 $sl=M("group_package_goods");
		 $dblist= $sl->where($where)->select(); //数据库当前主题存在的记录信息;
		 $aryadd=$arydel=$aryupd=array();
		 //提交数据 是否在数据库中存在，存在更新否则增加
		 foreach($json as $k=>$v){ 
		 	$flg=0;
		 	$v["packageid"]=$where['packageid'];
		 	foreach ($dblist as $key=>$o){ 
		 		if($v["pgid"]==$o['pgid'] && $v["goodsid"]==$o['goodsid']){
		 			$aryupd[]=$v;				  
		 			$flg=1;
		 			break;
		 		}
		 	}
		 	if($flg==0){
		 		$v["packageid"]=$where['packageid'];
		 		$v["pgid"]=getGuid();
		 		$aryadd[]=$v;
		 	}
		 }
		 
		 //在数据库里存在，但是提交的数据不存在，删除数据
		 foreach ($dblist as $key=>$o){
		 	$bl=0;
		 	foreach($json as $k=>$v){
		 		if($v["pgid"]==$o['pgid'] && $v["goodsid"]==$o['goodsid']){ 
		 			$bl=1;
		 			break;
		 		}
		 	}
		 	if($bl==0){
		 		$arydel[]=$o;
		 	}
		 }

		 $sqladd=$sqlupd=$sqldel="";
		 $arysqlupd=array();  
		 $time=date("Y-m-d H:i:s");
		 


		 //构建插入数据语句
		 if(count($aryadd)>0){
		 	$sqlval=""; 
		 	foreach ($aryadd as $k=>$v){
		 		//$listid=getGuid();//创建guid值
		 		//$money = intval($v['number'])*$v['price'] + $v['logistics_price']*$v['weight'];
		 		$sqlval.=((empty($sqlval)?"":",")."('".$v['pgid']."','".$v['packageid']."','".$v['goodsid']."','".$v['number']."','".$v['saleprice']."','".$v['userprice']."','".$v['vipprice']."','".$data['blongtype']."',".$_SESSION['admin_id'].",'$time')");
		 	}
		 	$sqladd=" INSERT INTO  ".$this->dbprefix."group_package_goods(`pgid`,`packageid`,`goodsid`,`number`,`saleprice`,`userprice`,`vipprice`,`blongtype`,`adminuserid`,`addtime`) values ".$sqlval;
		 }
		 
		 //构建更新数据语句
		 if(count($aryupd)>0){  
		 	foreach ($aryupd as $k=>$v){
		 		//$money = intval($v['number'])*$v['price'] + $v['logistics_price']*$v['weight'];
		 		$sqlupd="update ".$this->dbprefix."group_package_goods set packageid='".$v['packageid']."',goodsid='".$v['goodsid']."',number='".$v['number']."',saleprice='".$v['saleprice']."',userprice='".$v['userprice']."',vipprice='".$v['vipprice']."',blongtype='".$data['blongtype']."',adminuserid='".$_SESSION['admin_id']."',addtime='".$time."' where pgid='".$v['pgid']."'";
		 		$arysqlupd[]=$sqlupd;
		 	} 
		 }

		 //构建删除数据语句
		 if(count($arydel)>0){
		 	$sqlval="";
		 	foreach ($arydel as $k=>$v){
		 		$sqlval.=((empty($sqlval)?"":",").$v['pgid']);
		 	}
		 	if(!empty($sqlval))
		 		$sqldel="delete from ".$this->dbprefix."group_package_goods where FIND_IN_SET(pgid,'".$sqlval."')";
		 }
		 
		 $db=M("group_package_goods");
		 $retadd=$retupd= $retdel=1; //默认是成功状态
		 
		 $db->startTrans(); //启动事务
		 
		 if($sqladd){
		 	$retadd=$db->execute($sqladd);
		 } 
		 
		 if(count($arysqlupd)>0){
		 	foreach ($arysqlupd as $k=>$sql){
		 		if(empty($sql))continue;
		 		$retupd=$db->execute($sql);
			    //如果失败就退出循环，失败
		 		if(!$retupd){
		 			break;  
		 		}
		 	}
		 }
		 
		 if($sqldel){
		 	$retdel=$db->execute($sqldel);
		 }
		 
		 if($retadd && $retupd && $retdel && $retgroup && $gmadd && $gmupd){
		 	$m->commit();
		 	$gm->commit();
		 	$db->commit();
		 	$ret=array('staute'=>'success','msg'=>"保存数据成功");
		 }
		 else {
		 	$m->rollback();
		 	$gm->rollback();
		 	$db->rollback();
		 	$ret=array('staute'=>'error','msg'=>"保存数据失败");
		 }	 
		 $this->ajaxReturn($ret);
		}

	//系统随机抽选开团人员
		public function setUser($packageid,$loop){

			$db = M();
			$user_id_arr = $db->query("SELECT userid FROM ".$this->dbprefix."group_system_user WHERE isactive =1 ORDER BY RAND() LIMIT ".$loop);
			foreach ($user_id_arr as $key => $value) {
				/*$value = "getGuid(),$packageid,$user_id_arr[$key],1,date(),adminuserid";*/
            //$sqlval.=((empty($sqlval)?"":",")."('".$v['pgid']."','".$v['packageid']."','".$v['goodsid']."','".$v['number']."','".$v['saleprice']."','".$v['userprice']."','".$v['vipprice']."','".$data['blongtype']."',".$_SESSION['admin_id'].",'$time')");
				$sqlval.=((empty($sqlval)?"":",")."('".getGuid()."','".$packageid."','".$value['userid']."','1','".date("Y-m-d H:i:s")."','".UID."')");
		 	//找到这个人在该用户的num +1
		 	//$db->query("UPDATE  ".$this->dbprefix."group_system_user  SET  num = num+1  WHERE `userid`= ".$value['userid']);
				D('group_system_user')->where("userid = '".$value['userid']."'")->setInc("num");
			}
			$sqladd=" INSERT INTO  ".$this->dbprefix."group_list(`listid`,`packageid`,`userid`,`iscreate`,`addtime`,`adminuserid`) values ".$sqlval;
			$m=M("group_list");
		 $retadd =1; //默认是成功状态
		 
		 $m->startTrans(); //启动事务

		 if($sqladd){
		 	$retadd=$db->execute($sqladd);
		 } 

		 if($retadd){
		 	$m->commit();
		    //将$user_id_arr 的第一个用户插入到ki_group_purchase_package 作为开团人
		 	$where['userid'] = $user_id_arr[0]['userid'];
		 	$userid=D('group_purchase_package')->where(" packageid = '".$packageid."'")->save($where);
		 }
		}

		public function checkGroups(){

			extract($_POST);
			$where['packageid']=array("in",$id);
			$m=M("group_package_order");
			$r=$m->where($where)->find();
			$rt=M("cart")->where($where)->find();
			if($r || $rt)
			{
				$result['status']=1;
			}
			else
			{
				$result['status']=0;
			}
			$this->ajaxReturn($result);
			exit;

		}

		public function checkGroup(){

			extract($_POST);
			$result['status']=0;
			$whereis['packageid']=$where['packageid']=$wheres['packageid']=array("in",$id);
			$wheres['status']=array("eq",1);
			$m=M("group_package_order");
			$r=$m->where($wheres)->find();
			$rt=M("cart")->where($where)->find();
			if($r || $rt)
			{
				$result['status']=1;
			}
			$whereis['usertype']=0;
			$whereis['isactive']=1;
			$isactive=D('group_purchase_package')->where($whereis)->select();
			if(!empty($isactive))
			{
				$result['status']=1;
			}
			$where['endtime']=array("gt",date("Y-m-d H:i:s"));
			$res=D('group_purchase_package')->where($where)->select();
			if(empty($res))
			{
				//可以更改
				$result['status']=0;
			}
			$this->ajaxReturn($result);
			exit;

		}
        //取消审核
		public function toExamine()
		{
			extract($_POST);
			$where['usertype']=0;
			$where['packageid']=array("in",$id);
			$m=M("group_purchase_package");
			$m->startTrans();
			$rs=1;
			if($type=="del")
			{
				$data['isactive']=0;
				$wheres['packageid']=$where_car['packageid']=array("in",$id);
				$wheres['status']=array("eq",1);
				$r=M("group_package_order")->where($wheres)->getField("packageid",true);
				$rt=M("cart")->where($where_car)->getField("packageid",true);
				if(!empty($r) || !empty($rt))
				{
					if(is_array($id))
					{
						foreach($id as $key => $val)
						{
							$flag=0;
							foreach($r as $key1 => $val1)
							{
								if($val == $val1)
								{
									$flag=1;
									break;
								}
							}
							foreach($rt as $key2 => $val2)
							{
								if($val == $val2)
								{
									$flag=1;
									break;
								}
							}
							if(!$flag)
							{
								$results[]=$val;
							}
						}
					}
					else
					{
						if(in_array($id,$r) || in_array($id,$rt) )
						{
							$results='';
						}
					}
					if(empty($results))
					{
						$result['status']=0;
						$result['message']="操作失败！该团正在进行不能取消审核";
						$this->ajaxReturn($result);
						exit;
					}
					$where['packageid']=array("in",$results);
				}
				if(count($id)>1)
					$result['message']="操作成功,有些团正在进行不能取消审核";
				else
				{
					$result['message']="操作成功";
				}
			}
			else
			{
				$data['isactive']=1;
				$result['message']="操作成功";
			}
			$rs=$m->where($where)->save($data);
			if($rs)
			{
				$m->commit();
				$result['status']=1;
			}
			else
			{
				$m->rollback();
				$result['status']=0;
				$result['message']="操作失败！";
			}
			$this->ajaxReturn($result);
			exit;
		}
		public function doDels(){
			extract($_POST);
			//foreach($id as $key => $val)
			//{
			//	$ids.="'".$val."',";
			//}
			//$ids=rtrim($ids,",");
			$where_p['packageid']=array("in",$id);
			$where_p['endtime']=array("gt",date("Y-m-d H:i:s"));
			//删除在购物车里没有的或者订单里面取消的，并且结束时间还么过去了的团
			//$packageids=M("group_purchase_package")->where("endtime < '".date("Y-m-d H:i:s")."'and packageid in(".$ids.") and (usertype = 0 and isactive = 0)")->getField("packageid",true);
			$packageids=M("group_purchase_package")->where($where_p)->getField("packageid",true);
			if(!empty($packageids))
			{
				$results=array();
				$where['packageid']=array("in",$packageids);
				$packageids_cart=M("cart")->where($where)->getField("packageid",true);
				$where['status']=array("neq",3);
				$packageids_order=M("group_package_order")->where($where)->getField("packageid",true);
				if(!empty($packageids_cart) || !empty($packageids_order))
				{
					foreach($packageids as $key => $val)
					{

						$flag=0;
						foreach($packageids_cart as $key1 => $val1)
						{
							if($val == $val1)
							{
								$flag=1;
								break;
							}
						}
						foreach($packageids_order as $key2 => $val2)
						{
							if($val == $val2)
							{
								$flag=1;
								break;
							}
						}
						if(!$flag)
						{
							$results[]=$val;
						}
					}
				}
				else
				{
					$results=$packageids;
				}
			//var_dump($packageids_res);
			//var_dump($results);
				$where_p['endtime']=array("lt",date("Y-m-d H:i:s"));
				$packageids_del=M("group_purchase_package")->where($where_p)->getField("packageid",true);
				if(empty($results))
				{
					array_merge($packageids_del,$results);
					$packageids_res=$packageids_del;
				}
				else
				{
					array_merge($results,$packageids_del);
					$packageids_res=$results;
				}
				if(empty($packageids_res))
				{
					$result['status']=0;
					$result['message']="操作失败,有些团正在进行不能删除";
					$this->ajaxReturn($result);
					exit;
				}
			}
			else
			{
				$packageids_res=$id;
			}
			
			$where['packageid']=array("in",$packageids_res);
			$data['isactive']=3;
			$r=M("group_purchase_package")->where($where)->save($data);
			if($r)
			{
				$result['status']=1;
				$result['message']="操作成功,有些团正在进行不能删除";
			}
			else
			{
				$result['status']=0;
				$result['message']="操作失败！";
			}
			$this->ajaxReturn($result);
			exit;
		}

		public function delGroup()
		{
			extract($_POST);
			$where['packageid']=array("in",$id);
			$m=M("group_purchase_package");
			$db=M("group_package_goods");
		 $m->startTrans(); //启动事务
		 //$db->startTrans(); //启动事务
		 $r=$ret=1;
		 $data['isactive']=3;
		 //$r=$m->where($where)->delete();
		 $r=$m->where($where)->save($data);
		 //$ret=$db->where($where)->delete();
		 if($r && $ret)
		 {
		 	$m->commit();
		    //$db->commit();
		 	$result['status']=1;
		 	$result['message']="操作成功";
		 }
		 else
		 {
		 	$m->rollback();
		    //$db->rollback();
		 	$result['status']=0;
		 	$result['message']="操作失败！";
		 }
		 $this->ajaxReturn($result);
		 exit;
		}



		public function iscomplete(){
			extract($_POST);
			$m=M("group_purchase_package");
			$where['packageid']=$id;
			$list = $m->where($where)->find();
			if($list['isactive']!=1){
				$result['status']=0;
				$result['message']="该包裹无效，请先去审核！";
			}else{
				$time = date("Y-m-d H:i:s");
				if($list['endtime']>$time){
					$result['status']=0;
					$result['message']="该包裹还未结束，请结束后完成！";
				}else{
					$re = $m ->where($where)->setField('is_complete','1');
					if($re){
						$result['status']=1;
						$result['message']="操作成功";
					}else{
						$result['status']=0;
						$result['message']="操作失败！";
					}
				}
			}
			$this->ajaxReturn($result);
			exit;

		}
		public function groupPic($group_desc,$input_value = ''){

			$kindeditor="<script charset='utf-8' src='/includes/kindeditor/kindeditor-min.js'></script>
			<script>
				var editor;
				KindEditor.ready(function(K) {
					editor = K.create('textarea[name=\"$group_desc\"]', {
						allowFileManager : true,
						width : '800px',
						height: '400px',
						afterCreate: function () {
							var self = this;
							this.sync();

						}, afterChange: function () {
							this.sync();
						}

					});
});

</script>
<textarea id=\"$group_desc\" name=\"$group_desc\" style='width:700px;height:300px;'>$input_value</textarea>
";
            $this->assign('FCKeditor', $kindeditor);  //这里前面的 FCKEditor 不要变 
        }


        public function choosePics(){

			//系统消息  => system_message

        	$module = empty($_REQUEST['module'])?'no_group':$_REQUEST['module'];

// 	$maxWidth = $_REQUEST['maxWidth'];
// 	$isNeedOrg = $_REQUEST['isNeedOrg']

	$maxWidth = 400;//$module_config[$module]['maxWidth'];


	$isNeedOrg = "group";//$module_config[$module]['isNeedOrg'];
	$only_choose_one = isset($_REQUEST['only_choose_one'])?$_REQUEST['only_choose_one']:'';
	$isNeedWatch = '';//$module_config[$module]['isNeedWatch'];
	$type = 'details';//$_REQUEST['type'];

	$this->assign('isNeedWatch',$isNeedWatch);
	$this->assign('_only_choose_one',$only_choose_one);
	$this->assign('isNeedOrg',$isNeedOrg);
	$this->assign('module',$module);
	$this->assign('maxWidth',$maxWidth);
	$this->assign('type',$type);
	$this->assign('tag',isset($_REQUEST['tag'])?trim($_REQUEST['tag']):'gallery_img');
	$this->display('uploadFiles');

}

public function uploadFiles(){

			//是否需要原图
// 	$isNeedOrg=$_REQUEST['isNeedOrg'];
// 	//原图最大宽度
	$maxWidth = $_REQUEST['maxWidth']; 
	//模块名
	$module = $_REQUEST['module'];

	$isNeedOrg = "";
	//$maxWidth = $module_config[$module]['maxWidth'];

	/* 上传文件 */
	/* 此乃回调函数配置是也 */
	$ATTACHMENT_UPLOAD['callback'] = array('Upload','isFile');
	$ATTACHMENT_UPLOAD['removeTrash'] = array('Upload','removeTrash');

	/* 返回标准数据 */
	$return  = array('status' => 1, 'info' => '上传成功', 'data' => '');

	//模块名称
	//$ATTACHMENT_UPLOAD['module'] = $module_name = $module;

	//设置路径
	$files=$_FILES;
	$upload=new \Think\Upload($ATTACHMENT_UPLOAD, 'local', array());
	
	$upload->maxSize   =     3145728 ;// 设置附件上传大小
	$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	$upload->rootPath  =      'Public/uploads/'; // 设置附件上传目录
	$upload->savePath  =      "{$module}/"; // 设置附件上传目录
	$path=$upload->rootPath.$upload->savePath;
	if(!is_dir($path) or
		!is_writable ($path) ){
		mk_dir($path,0777);
}
$info   =   $upload->upload($files);
	if($info){ //文件上传成功，记录文件信息

		$data['attachment_name']=$info['download']['name'];
		$data['file_name']=$info['download']['savepath'].$info['download']['savename'];
			$data['module'] = $module;//存储模块名称
			$data['file_size'] = $info['download']['size'];
			$data['file_extension_name'] = $info['download']['ext'];
			$data['create_time']=time();
			$data['create_uid']=$_SESSION['admin_id'];
			$attachment_id=M("attachment")->add($data);
			//如果是图片就压缩图片，并把压缩后的图片大小记录到数据库
			//缩小图片的插件
			//引用的tp的图片处理类
			//include_once('./plugins/Image/Image.class.php');

			if(!empty($attachment_id)){
				$imgSize =  getimagesize($upload->rootPath.$data['file_name']);
				//生成缩略图的操作类
				$image = new \Think\Image();
				//打开原图
				$image->open($upload->rootPath.$data['file_name']);
				//如果原图片宽度大于$maxWidth就将原图压缩为$maxWidthx$maxWidth的缩略图并替换保存
				if( $imgSize[0]>$maxWidth && !empty($maxWidth) ){
					// 按照原图的比例生成一个最大为$maxWidth*$maxWidth的缩略图并保存为缩略图
					$image->thumb($maxWidth, $maxWidth)->save($path.$data['file_name']);
				}

				//如果有需要原图就生成缩略图，否则不生成
				if(!empty($isNeedOrg)){
					// 按照原图的比例生成一个最大为$ATTACHMENT_UPLOAD['thumb_width']*$ATTACHMENT_UPLOAD['thumb_height']
					// 的缩略图名称一样
					$image->thumb($ATTACHMENT_UPLOAD['thumb_width'], $ATTACHMENT_UPLOAD['thumb_height'])
					->save($_thumb_path);
				}

				//上传的附件id
				$data['id']=$attachment_id;
				$return=array_merge($return,$data);
				//文件上传成功
				$return['info']=$info['download']['name'];
				
				
			}else{
				$return['status'] = 0;
				$return['info'] = '上传失败';
			}
		}

		else {
			$return['status'] = 0;
			$return['info'] = $upload->getError();
		}
		/* 返回JSON数据 */
		echo json_encode($return);
		exit;
		
	}
	
	
	public function query(){
		$page = isset($_REQUEST['page'])?intval($_REQUEST['page']):1;
		$rows = 50;
		$module = $_REQUEST['module'];

		//$count_sql = " select count(*) from {$ecs->table('attachment')} where module ='{$module}' ";
		$count = M("attachment")->where("module ='{$module}'")->count();

		$total_page = ceil($count/50);//总页数
		$is_all = 0;
		if($total_page == $page)$is_all=1;

		$limit = (($page-1)*$rows).','.$rows;

		$lists =M('attachment')->where("module ='{$module}'")->order("id desc")->limit($limit)->select();

		echo json_encode(array('status'=>1,'lists'=>$lists,'is_all'=>$is_all));
		exit;
		
	}
	
	
	public function delPics(){
		$pic_id=$_REQUEST['id'];
		$pic_id = trim($pic_id);//去空格
		$pic_id=rtrim($pic_id,',');//去最后一个逗号
		//确定
		$is_confirm = isset($_REQUEST['is_confirm'])?intval($_REQUEST['is_confirm']):0;

		if(empty($pic_id)){
			echo json_encode(array('status'=>0,'info'=>'参数错误'));
			exit;
		}
		$result=M("attachment")->alias("a")->join("inner join ".$this->dbprefix."group_gallery as gg on gg.img_url = a.file_name inner join ".$this->dbprefix."group_purchase_package as gpp on gg.packageid = gpp.packageid")->where("a.id in (".$pic_id.")")->field("a.attachment_name as file_name,gpp.packagename,a.id as atta_id")->select();
		
		if( (count($result)>0) &&  ($is_confirm == 0)){
			echo json_encode(array('status'=>-1,'info'=>'图片已被产品使用不能删除!','data'=>$result));
			exit;
		} 
		//图片列表

		$results=M("attachment")->where("id in (".$pic_id.")")->select();

	   //删除附件表
		$r =M("attachment")->where("id in (".$pic_id.")")->delete();

		if($r){

			foreach($results as $v){
				//循环删除图片
				@unlink('Public/uploads/'.$v['file_name']);
				M("group_gallery")->where("img_url = '".$v['file_name']."'")->delete();
				//@unlink(ROOT_PATH.'/attas/orgimg/'.$v['file_name']);
			}

			echo json_encode(array('status'=>1,'info'=>'操作成功'));
			exit;
		}else{
			echo json_encode(array('status'=>0,'info'=>'操作失败'));
			exit;
		}
	}

	public function delete_img(){

			$img_id = $_REQUEST['img_id'];//详情图片ID
			M('group_gallery')->where("img_id=".intval($img_id))->delete();
			
		}
		
	//报订单
		public function order_info(){
			$packageid = $_REQUEST['packageid'];
			//获取到所有的发起人的名字（便于查看发起人包的所有成员）
			$list = D('group_list')->field('a.listid,b.user_name,b.nickname,a.userid')->alias('a')->join(' inner join '.$this->dbprefix.'users b on a.userid=b.user_id')->where("a.packageid='".$packageid."'")->select();
			$this->assign('user_list',$list);
			$this->assign('packageid', $packageid);
			$this->display();
		}




		public function order_info_list(){
			$packageid = $_REQUEST['packageid'];
			$_listrows = I('request._listrows', '', 'trim');
			$keywords = I('request.keywords','','trim');
			$listid = $_REQUEST['listid'];
			if($listid)
			{
				$_where['a.listid'] = $listid;
			}
			$_where['a.packageid'] = $packageid;
			$_where['a.status'] = 1;
			if(!empty($keywords)){
				$_where['o.order_sn|c.user_name']=array('like',"%{$keywords}%");

			}
			$start_time = I('request.start_time','','trim');
			$end_time = I('request.end_time','','trim');
			$str='';
        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值 
			if(!(empty($start_time) && empty($end_time))){ 
				$start_time = empty($start_time)?date("Y-m-d"):$start_time;
				$end_time = empty($end_time)?date("Y-m-d"):$end_time;
				if($start_time>$end_time){
					$temp=$end_time;
					$end_time=$start_time;
					$start_time=$temp;
				}  
				$str =" and a.addtime between '".$start_time." 00:00:01' and '".$end_time." 23:59:59'"; 
			}  

			$str = ltrim(trim($str),'and');
			if(!empty($str)){
				$_where['_string']=$str;
			}
			$where_order['where'] = $_where;
			/*$where_order['order'] = ' last_transaction_time desc ';*/
			$where_order['listrows'] = $_listrows;
			$where_order["id"]="load_tb_div";
			$where_order["alias"]="a";
			$where_order["order"]="a.addtime desc";
			$where_order["field"]="a.*,b.packagename,b.blongtype,c.user_name,o.order_sn,o.pay_status,o.consignee";
			$where_order["join"]=array('inner join '.$this->dbprefix.'group_purchase_package b on a.packageid=b.packageid',
				' inner join '.$this->dbprefix.'order_info o on a.orderid=o.order_id' ,
				' inner join '.$this->dbprefix.'users c on o.user_id=c.user_id');  
			$_datalist = $this->_getListsFromModel('group_package_order', $where_order);
			$this->assign('_datalist', $_datalist);
			$this->display();

		}


//添加发起人
		public function add_promoter(){
			$packageid = $_REQUEST['packageid'];
			$this->assign('packageid', $packageid);
			$this->display();
		}


		public function add_promoter_list(){
			$packageid = $_REQUEST['packageid'];
			$_listrows = I('request._listrows', '', 'trim');
			$keywords = I('request.keywords','','trim');
			if(!empty($keywords)){
				$_where['c.user_name']=array('like',"%{$keywords}%");

			}

			/*	 $map['id'] = array ('in',$getid);*/
			$ids = $this->get_user_id_arr($packageid);
			if(!empty($ids)){
				$_where['userid'] = array('not in',$ids);
			}

			$where_order['where'] = $_where;
			/*$where_order['order'] = ' last_transaction_time desc ';*/
			$where_order['listrows'] = $_listrows;
			$where_order["id"]="load_tb_div";
			$where_order["alias"]="a";
			$where_order["order"]="a.addtime desc";
			$where_order["field"]="a.*,c.user_name,c.nickname,c.is_vip";
			$where_order["join"]=array(
				' inner join '.$this->dbprefix.'users c on a.userid=c.user_id');  
			$_datalist = $this->_getListsFromModel('group_system_user', $where_order);
			/*print_r($_datalist);exit;*/

			$sql="select count(distinct(gpo.listid)) as count from ".$this->dbprefix."group_list as gl inner join ".$this->dbprefix."group_package_order as gpo on gpo.listid = gl.listid where gl.iscreate = 0 and  gpo.status = 1 and gl.packageid ='".$packageid."' and gpo.packageid ='".$packageid."'";
			$count_num=M()->query($sql);
         //看这个包有多少个人
			$count_user = D('group_list')->where("packageid = '".$packageid."' and iscreate = 1")->count();
			$count_user=($count_user)?$count_num[0]['count']+$count_user:$count_num[0]['count'];
         //查询这个包最大多少人
			$groupnumber = D('group_purchase_package')->field('groupnumber')->where("packageid = '".$packageid."'")->find();
         //包的人数小于包的最大人数的时候  才能添加发起人
			if($count_user <$groupnumber['groupnumber']){
				$num = $groupnumber['groupnumber'] - $count_user;
				$this->assign('num', $num);
				$this->assign('_datalist', $_datalist);
			}
			$this->display();;
		}


		public function set_add_promoter_list(){

	    //这里只有添加
			$ret=array('staute'=>'error','msg'=>"保存失败");
			$packageid=$_POST['packageid'];
			$postdata=I("json");
			if(empty($packageid)||empty($postdata)){
				$ret=array('staute'=>'error','msg'=>"传输参数错误");
				$this->ajaxReturn ($ret);
				exit;
			} 
			
			$json = json_decode($postdata,true);
			if(!is_array($json)){
				$ret=array('staute'=>'error','msg'=>"发起人信息错误");
				$this->ajaxReturn ($ret);
				exit;
			}
			$retadd=1; //默认是成功状态
			$sqlval ="";
			foreach ($json as $key => $value) {
				$listid = getGuid();
				$sqlval.=((empty($sqlval)?"":",")."('".$listid."','".$packageid."','".$value['userid']."','1','".date("Y-m-d H:i:s")."','".UID."')");
			}
			$sqladd=" INSERT INTO  ".$this->dbprefix."group_list(`listid`,`packageid`,`userid`,`iscreate`,`addtime`,`adminuserid`) values ".$sqlval;
			$gl=M("group_list");
		 $gl->startTrans(); //启动事务
		 
		 if($sqladd){
		 	$readd= $gl->execute($sqladd);
		 } 
		 if($retadd){
		 	$gl->commit();
		 	$ret=array('staute'=>'success','msg'=>"保存数据成功");
		 }
		 else {
		 	$gl->rollback();
		 	$ret=array('staute'=>'error','msg'=>"保存数据失败");
		 }	 
		 $this->ajaxReturn($ret); 	
		}
		

		public function get_user_id_arr($packageid){
             //查询该包是否有发起人 
			$sqllist = D('group_list')->field('userid')->where("packageid = '".$packageid."'")->select();
			if($sqllist ==""){
				return;
			}
			$user_ids = array();
			foreach ($sqllist as $key => $value) {
				$user_ids[] =$value['userid'];
			}
			return $user_ids;
		}


	}







	?>